package org.managedbeans;

import java.io.Serializable;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

import org.apache.tomcat.util.codec.binary.Base64;
import org.info.PersonInfo;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

@ManagedBean(name="personMB")
@RequestScoped
public class PersonMB implements Serializable{

	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private PersonInfo info;
	private String urlDest = "https://eval-cloud2.castiron.com:443/env/Development/httpsend";
	private boolean ibm = false;
	
	
	@PostConstruct
	public void load(){
		
		info = new PersonInfo();
		
	}
	
	
	public String send(){
		
		Gson gson = new Gson();
		String content = gson.toJson(info);
		
//		admin@eval.4shp
//		Grupo2tsi4
		
		  try {
			  	String authorization = "";
				URL url = new URL(urlDest);
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.setDoOutput(true);
				conn.setRequestMethod("POST");
				conn.setRequestProperty("Content-Type", "application/json");
				if (ibm){
		            authorization = "admin@eval.4shp:Grupo2tsi4";
		            byte[] encodedBytes;
		            encodedBytes = Base64.encodeBase64(authorization.getBytes());
		            authorization = "Basic " + new String(encodedBytes);
		            conn.setRequestProperty("Authorization", authorization);
				}
				OutputStream os = conn.getOutputStream();
				os.write(content.getBytes());
				os.flush();
		 
				if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED && (conn.getResponseCode() != HttpURLConnection.HTTP_OK)) {
					throw new RuntimeException("Failed : HTTP error code : "
						+ conn.getResponseCode());
				}
		 
				BufferedReader br = new BufferedReader(new InputStreamReader(
						(conn.getInputStream())));
		 
				String output;
				System.out.println("Output from Server .... \n");
				while ((output = br.readLine()) != null) {
					System.out.println(output);
				}
		 
				conn.disconnect();
		 
			  } catch (MalformedURLException e) {
		 
				e.printStackTrace();
		 
			  } catch (IOException e) {
		 
				e.printStackTrace();
		 
			 }
		 
		return null;
	}
	

	public PersonInfo getInfo() {
		return info;
	}

	public void setInfo(PersonInfo info) {
		this.info = info;
	}
	
	public String getUrlDest() {
		return urlDest;
	}


	public void setUrlDest(String urlDest) {
		this.urlDest = urlDest;
	}


	public boolean isIbm() {
		return ibm;
	}


	public void setIbm(boolean ibm) {
		this.ibm = ibm;
	}
	
}


